<?php
namespace app\index\controller;
use think\Request;


class Index extends Base
{
	private $cate;

	public function _initialize(){
		parent::_initialize();
		$this->cate = Model('Category');
		$this->fang = Model('Fang/fang');
	}
/**
 *  递归获取所有分类
 */
    public function menuTree($arr,$pid=0,$level=0){
        static $tree = array();
        foreach ($arr as $v) {
            if ( $v['pid'] == $pid) {
                $v['level'] = $level;
                $v['catename'] = '├ ' . str_repeat('---- ',$level) . $v['catename'];
                $tree[] = $v;
                $this->menuTree($arr,$v['id'],$level+1);
            }
        }
        return $tree;
    }

	public function index(){
		$request = Request::instance();
		$total = $this->fang->count();
		
		$list 		= $this->cate->getList();
		$list 		= $this->menuTree($list);
		$li 	= '';

		$f_countbycate = array();
		foreach ($list as $v) {
			$li .= '<li><a href="/index.php' . url('index/getinfo',Array('id'=>$v['id'])) . '"><span class="glyphicon glyphicon-list-alt"></span>' . $v['catename'] . '</a></li>';
			$f_countbycate[] = [
				'catename' => $v['catename'],
				'count' => $this->getCount($v['id']),
				'id' => $v['id']
			];
		}

		$this->assign('li',$li);
		$this->assign('total',$total);
		$this->assign('f_countbycate',$f_countbycate);
		return $this->fetch();
	}

	public function getinfo($id){
		$where = [
			'cateid' => $id,
		];
		$order = [
			'id' => 'desc'
		];
		
		$info = $this->fang->where($where)->order($order)->paginate($this->pagecount);
		$page = $info->render();

		$list 		= $this->cate->getList();
		$list 		= $this->menuTree($list);
		// var_dump($list);die;
		$li 	= '';

		foreach ($list as $v) {
			if ( $v['level'] == 0) {
				$li .= '<li><span class="glyphicon glyphicon-list-alt"></span><strong>' . $v['catename'] . '</strong></li>';
			}else{
				$li .= '<li><a href="' . url('index/getinfo',Array('id'=>$v['id'])) . '"><span class="glyphicon glyphicon-list-alt"></span>' . $v['catename'] . '</a></li>';
			}
			
		}

		$catename = $this->getCateName($id);

		$this->assign('catename',$catename);
		$this->assign('li',$li);
		$this->assign('info',$info);
		$this->assign('page',$page);
		return $this->fetch();
	}

	public function getCateName($id){
		$res = $this->cate->getOne($id);
		return $res['catename'];
	}

	public function s(){

		$cates 		= $this->cate->getList();
		$option 	= '';
		foreach ($cates as $v) {
			$option .= '<option value="' . $v['id'] .'">' . $v['catename'] . '</option>';
		}
		
		$list 		= $this->cate->getList();
		$li 	= '';

		foreach ($list as $v) {
			$li .= '<li><a href="/index.php/Index/index/getinfo/id/' . $v['id'] . '"><span class="glyphicon glyphicon-list-alt"></span>' . $v['catename'] . '</a></li>';
		}

		$this->assign('li',$li);
		$this->assign('option',$option);
		return $this->fetch();
	}

	public function getCount($cateid){
		$where = [
			'cateid' => $cateid,
		];
		$count = $this->fang->where($where)->count();
		return $count;
	}
}